<?php

namespace app\api\controller\order;

use app\api\model\file\UploadFile;
use app\api\model\order\Cart as CartModel;
use app\api\model\order\Order as OrderModel;
use app\api\model\order\OrderReferee as OrderRefereeModel;
use app\api\model\product\Product as ProductModel;
use app\api\model\stall\Apply as ApplyModel;
use app\api\model\store\Store;
use app\api\model\user\UserAddress;
use app\api\service\order\settled\MasterOrderSettledService;
use app\api\controller\Controller;
use app\api\model\settings\Message as MessageModel;
use app\api\service\pay\PayService;
use app\common\enum\order\OrderTypeEnum;
use app\common\library\helper;
use app\api\model\settings\Setting as SettingModel;
use app\common\model\app\App as AppModel;
use app\Request;

/**
 * 普通订单
 */
class Order extends Controller
{
    /**
     * 订单确认-立即购买
     */
    public function buy()
    {
        // 立即购买：获取订单商品列表
        $params = json_decode($this->postData()['params'], true);

        $supplierData = OrderModel::getOrderProductListByNow($params);
        $user = $this->getUser();
        // 实例化订单service
        $orderService = new MasterOrderSettledService($user, $supplierData, $params);
        // 获取订单信息
        $orderInfo = $orderService->settlement();

        // 订单结算提交
        if ($orderService->hasError()) {
            return $this->renderError($orderService->getError());
        }
        if ($this->request->isGet()) {
            // 如果来源是小程序, 则获取小程序订阅消息id.获取支付成功,发货通知.
            $template_arr = MessageModel::getMessageByNameArr($params['pay_source'], ['order_pay_user', 'order_delivery_user']);
            //是否显示店铺信息
            $store_open = SettingModel::getStoreOpen();
            // 是否开启支付宝支付
            $show_alipay = PayService::isAlipayOpen($params['pay_source'], $user['app_id']);
            $balance = $user['balance'];
            //起送价
            $need_delivery = OrderModel::checkStoreDelyPrice($orderInfo);
            $in_delivery = ($need_delivery > 0);

            return $this->renderSuccess('', compact('orderInfo', 'template_arr', 'store_open', 'show_alipay', 'balance','in_delivery','need_delivery'));
        }
        $orderInfo['orderData']['store_id'] = $params['store_id'];
        $orderInfo['orderData']['buytype'] = $params['buytype']??'';
        $orderInfo['orderData']['yypstime'] = $params['yypstime']??'';
        if(isset($params['stall_id'])&&$params['stall_id']>0){
            $addr = ApplyModel::getdetail($params['stall_id']);
            $addr['name'] = $params['real_name']??'';
            $addr['phone'] = $params['real_phone']??'';
            if (empty($addr)) return $this->renderError($orderService->getError() ?: '地址异常');
            $orderInfo['orderData']['stall_id'] = $params['stall_id'];
            $orderInfo['orderData']['address'] = $addr;
        }else {
            if (array_key_exists('addr_id', $params)) {
                $addr = UserAddress::where('address_id', '=', $params['addr_id'])->find();
                if (empty($addr)) return $this->renderError($orderService->getError() ?: '地址异常');
                $orderInfo['orderData']['address'] = $addr;
            }
        }
        $checkPTS = OrderModel::checkAddrPointToStore($addr,$params['store_id']);
        if(!$checkPTS){
            return $this->renderError($orderService->getError() ?: '地址不在店铺配送范围');
        }
        foreach ($orderInfo['supplierList'] as $sval) {
            $checkSWP = OrderModel::checkStoreWithProduct($params['store_id'],$sval['productList']);
            if(!$checkSWP){
                return $this->renderError($orderService->getError() ?: '地址不在店铺配送范围');
            }
        }
        //检测休息
        $checkXX = OrderModel::checkStoreRest($params['store_id']);
        if(!$checkXX){
            return $this->renderError($orderService->getError() ?: '店铺已打烊休息');
        }
        //检测起送价
        $checkQSJ = OrderModel::checkStoreDelyPrice($orderInfo);
        if($checkQSJ>0){
            return $this->renderError($orderService->getError() ?: '未达到起送价格');
        }
        // 创建订单
        $order_id = $orderService->createOrder($orderInfo);
        if (!$order_id) {
            return $this->renderError($orderService->getError() ?: '订单创建失败');
        }

        // 返回订单信息
        return $this->renderSuccess('', [
            'order_id' => $order_id,   // 订单号
        ]);
    }

    /**
     * 订单确认-立即购买
     */
    public function cart()
    {
        // 立即购买：获取订单商品列表
        if ($this->request->isGet()) {
            $params = json_decode($this->postData()['params'], true);
        } else {
            $params = json_decode($this->postData()['params'], true);
        }
        $user = $this->getUser();
        // 商品结算信息
        $CartModel = new CartModel();
        // 购物车商品列表
        $supplierData = $CartModel->getList($user, $params['cart_ids'], $params['stall_id']??0);
        // 实例化订单service
        $orderService = new MasterOrderSettledService($user, $supplierData, $params);
        // 获取订单信息
        $orderInfo = $orderService->settlement();
        if ($this->request->isGet()) {
            // 如果来源是小程序, 则获取小程序订阅消息id.获取支付成功,发货通知.
            $template_arr = MessageModel::getMessageByNameArr($params['pay_source'], ['order_pay_user', 'order_delivery_user']);
            //是否显示店铺信息
            $store_open = SettingModel::getStoreOpen();
            // 是否开启支付宝支付
            $show_alipay = PayService::isAlipayOpen($params['pay_source'], $user['app_id']);
            $balance = $user['balance'];
            //起送价
            $need_delivery = OrderModel::checkStoreDelyPrice($orderInfo);
            $in_delivery = ($need_delivery > 0);

            return $this->renderSuccess('', compact('orderInfo', 'template_arr', 'store_open', 'show_alipay', 'balance','in_delivery','need_delivery'));
        }
        if(isset($params['stall_id'])&&$params['stall_id']>0){
            $addr = ApplyModel::getdetail($params['stall_id']);
            $addr['name'] = $params['real_name']??'';
            $addr['phone'] = $params['real_phone']??'';
            if (empty($addr)) return $this->renderError($orderService->getError() ?: '地址异常');
            $orderInfo['orderData']['stall_id'] = $params['stall_id'];
            $orderInfo['orderData']['address'] = $addr;
        }else {
            if (array_key_exists('addr_id', $params)) {
                $addr = UserAddress::where('address_id', '=', $params['addr_id'])->find();
                if (empty($addr)) return $this->renderError($orderService->getError() ?: '地址异常');
                $orderInfo['orderData']['address'] = $addr;
            }
        }
        $checkPTS = OrderModel::checkAddrPointToStore($addr,$params['store_id']);
        if(!$checkPTS){
            return $this->renderError($orderService->getError() ?: '地址不在店铺配送范围');
        }
        foreach ($orderInfo['supplierList'] as $sval) {
            $checkSWP = OrderModel::checkStoreWithProduct($params['store_id'],$sval['productList']);
            if(!$checkSWP){
                return $this->renderError($orderService->getError() ?: '地址不在店铺配送范围');
            }
        }
        //检测休息
        $checkXX = OrderModel::checkStoreRest($params['store_id']);
        if(!$checkXX){
            return $this->renderError($orderService->getError() ?: '店铺已打烊休息');
        }
        // 订单结算提交
        if ($orderService->hasError()) {
            return $this->renderError($orderService->getError());
        }
        $orderInfo['orderData']['store_id'] = $params['store_id'];
        $orderInfo['orderData']['buytype'] = $params['buytype'];
        $orderInfo['orderData']['yypstime'] = $params['yypstime'];
        if (array_key_exists('addr_id', $params)) {
            $addr = UserAddress::where('address_id', '=', $params['addr_id'])->find();
            if (empty($addr)) return $this->renderError($orderService->getError() ?: '地址异常');
            $orderInfo['orderData']['address'] = $addr;
        }
        //检测起送价
        $checkQSJ = OrderModel::checkStoreDelyPrice($orderInfo);
        if($checkQSJ>0){
            return $this->renderError($orderService->getError() ?: '未达到起送价格');
        }
        // 创建订单
        $order_id = $orderService->createOrder($orderInfo);
        if (!$order_id) {
            return $this->renderError($orderService->getError() ?: '订单创建失败');
        }
        // 移出购物车中已下单的商品
        $CartModel->clearAll($user, $params['cart_ids']);
        // 返回订单信息
        return $this->renderSuccess('', [
            'order_id' => $order_id,   // 订单号
        ]);
    }

    public function checkScope(Request $request)
    {
        $where = $request->param();
        $storeList = OrderModel::checkScope($where);
        foreach ($storeList as &$item) {
            $distance_km = bcdiv($item['distance'], 1000, 2);
            $item['image_url'] = UploadFile::where('file_id', '=', $item['logo_image_id'])->find();
            if (intval($distance_km) > 0) {
                $item['distance'] = $distance_km . 'km';
            } else {
                $item['distance'] = intval($item['distance']) . 'm';
            }
        }
        return $this->renderSuccess('', compact('storeList'));
    }

    public function checkScopeAll(Request $request)
    {
        $where = $request->param();
        $storeList = OrderModel::checkScopeAll($where);
        foreach ($storeList as &$item) {
            $distance_km = bcdiv($item['distance'], 1000, 2);
            if (intval($distance_km) > 0) {
                $item['distance'] = $distance_km . 'km';
            } else {
                $item['distance'] = intval($item['distance']) . 'm';
            }
        }
        return $this->renderSuccess('', compact('storeList'));
    }

    /**
     * @Exp    获取邀请列表数据
     * @Author Mr.Z
     * @Date   2024-02-21
     * @return [type]     [description]
     */
    public function getinvitelist(Request $request)
    {
        // 当前用户信息
        $user = $this->getUser();
        $param = $request->param();
        $OrderRefereeModel = new OrderRefereeModel();
        $params = [];
        if($param['type']==1){//月
            $params['start_time'] = strtotime(date("Y-m-1",time()));
            $params['end_time'] = time();
        }elseif($param['type']==2){//日
            $params['start_time'] = time();
        }
        $list = $OrderRefereeModel->getList($user['user_id'],$params);
        return $this->renderSuccess('', $list);
    }

    /**
     * @Exp    检测配送地址-自动匹配选择
     * @param Request $request
     * @return \think\response\Json
     * @throws \app\common\exception\BaseException
     */
    public function selectaddress(Request $request){
        // 当前用户信息
        $user = $this->getUser();
        $param = $request->param();
        $product_id = $param['product_id'];
        $vuex_aid = $param['vuex_aid'];
        $address_id = 0;
        $store_id = 0;
        // 商品详情
        $product = ProductModel::detail($product_id);
        if($product){
            $shop_supplier_id = $product['shop_supplier_id'];
            $CheckReturn = OrderModel::checkUserAllAddress($user['user_id'],$shop_supplier_id,$vuex_aid);
            $address_id = $CheckReturn[0];
            $store_id = max($CheckReturn[1], 0);
        }
        return $this->renderSuccess('', [
            'address_id' => $address_id,
            'store_id' => $store_id
        ]);
    }


    public function checkstoreproducts(Request $request){
        $user = $this->getUser();
        $param = $request->param();
        $product_id = $param['product_id'];
        $address_id = $param['address_id'];
        $resary = [];
        if(!is_array($product_id)) $product_id = [$product_id];
        foreach ($product_id as $id) {
            $NewPid = ProductModel::selectChangeProduct($user,$id,$address_id);
            $resary[] = $NewPid;
        }
        $responeids = implode(",",$resary);
        return $this->renderSuccess('', [
            'productids' => $responeids
        ]);
    }

}
